import { app, BrowserWindow, protocol, dialog, Menu, Tray, ipcMain } from "electron";
let { Observable, Subject } = require("rxjs");
const env = process.env.NODE_ENV;
console.log("Program Start With Env: ", env);
const server = require("./server.electron");
const debug = require("debug")("Index");
const path = require("path");
const url = require("url");
const util = require("util");
const mime = require("mime");
const http = require("http");
const fs = require("fs");
const log = require('electron-log');

const TIPS = {
  "ERROR_UPDATE_FAIL": "获取更新文件失败，请检查您的网络连接",
  "ERROR_UPDATE_FAIL_WITH_CACHE": "获取更新文件失败，将在下次启动时再次检查更新",
  "ERROR_UPDATE_FAIL_WITHOUT_CACHE": "获取关键更新文件失败，程序无法正常运行，请检查您的网络连接并重试",
};
const TIP_TYPES = {
  "ERROR_UPDATE_FAIL": "更新失败",
};
const APP_DIR = "";
const APP_NAME = app.getName();

//设置全局变量，提供给各个子页面调用
global['logger'] = log;
global['appAgent'] = "allwin." + (process.platform == 'darwin' ? 'mac' : 'win') + '/' + app.getVersion();

// app auto updater
let ifShowUpdateMsgBox = false;
let isUpdating = false;
const {autoUpdater} = require("electron-updater");
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';

autoUpdater.on('checking-for-update', () => {
  //sendStatusToWindow('检查更新...');
  isUpdating = true;
})
autoUpdater.on('update-available', (info) => {
  sendStatusToWindow('发现新版本V' + info.version + '...');
})
autoUpdater.on('update-not-available', (info) => {
  sendStatusToWindow('_no_update');
  isUpdating = false;
})
autoUpdater.on('error', (err) => {
  sendStatusToWindow('更新出现异常 —— ' + err);
  isUpdating = false;
})
autoUpdater.on('download-progress', (progressObj) => {
  let log_message = "新版本下载中... " + progressObj.percent.toFixed(2) + '%';
  //let log_message = "Download speed: " + progressObj.bytesPerSecond;
  //log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
  //log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
  sendStatusToWindow(log_message);
})
autoUpdater.on('update-downloaded', (info) => {
  sendStatusToWindow('新版本V' + info.version + '下载已完成，下次运行时生效！');
  isUpdating = false;
  dialog.showMessageBox({
      title: '新版本下载完成',
      message: '新版本V' + info.version + '将在下次运行时生效。您也可以现在安装更新，并重新运行。',
      buttons: ['现在安装', '暂不安装']
    }, (response) => {
      if (response === 0) {
        sendStatusToWindow('正在退出，准备更新...');
        try {
          setImmediate(() => {
            autoUpdater.quitAndInstall(false);
            app.exit();
          })
        } catch (e) {
          dialog.showErrorBox('即时更新遇到问题', e.message);
        }
      }
    }
  );
});

let win;
let login;
let tray;
let debug_msg = "";

//load flash plugins
let ppapi_flash_path = (process.platform == 'darwin') ? '../../plugins/PepperFlashPlayer.plugin' : './plugins/pepflashplayer.dll';
ppapi_flash_path = path.join(__dirname, ppapi_flash_path);
if (!fs.existsSync(ppapi_flash_path)) {
  //debug_msg = "no:" + ppapi_flash_path;
  //兼容mac开发环境和打包后的路径差异
  ppapi_flash_path = (process.platform == 'darwin') ? './plugins/PepperFlashPlayer.plugin' : './plugins/pepflashplayer.dll';
}
app.commandLine.appendSwitch('ppapi-flash-path', ppapi_flash_path);
app.commandLine.appendSwitch('ppapi-flash-version', '22.0.0.192');

// 登陆部分逻辑
ipcMain.on("login", (e, url) => {
  login = new BrowserWindow({
    parent: win,
    // modal: true,
    show: false,
    webPreferences: {
      nodeIntegration: false
    }
  });
  // console.log("Login Url: ", url);
  login.loadURL(url);
  login.once("ready-to-show", () => {
    login.show();
  });
  login.on("page-title-updated", (e, arg) => {
    if (arg.indexOf(APP_NAME) !== -1) {
      login.hide();
      login = null;
      win.webContents.send("login-success");
    }
    // console.log("Page Title Update: ", e.sender, arg);
  });
});

const createMenu = () => {
  let template: any[] = [{
    label: APP_NAME,  // app.getName(),
    submenu: [
      {
        label: "检查更新",
        click() { checkUpdate(true); }
      },
      {
        type: "separator"
      },
      {
        role: "forcequit",
        label: '退出',
        accelerator: 'CmdOrCtrl+Q',
        click: function () {
          app.exit();
        }
      }
    ]
  },
  {
    label: '视图',
    submenu: [
      {
        label: "实际大小",
        role: 'resetzoom'
      },
      {
        label: "放大",
        role: 'zoomin'
      },
      {
        label: "缩小",
        role: 'zoomout'
      },
      {
        label: "全屏切换",
        role: 'togglefullscreen'
      }
    ]
  },
  {
    role: "window",
    label: "窗口",
    submenu: [
      {
        role: 'minimize',
        label: '最小化',
        accelerator: 'CmdOrCtrl+M',
      },
      {
        role: "close",
        label: "关闭窗口"
      }
    ]
  },
  {
    role: "help",
    label: "帮助",
    submenu: [
      {
        label: "官网在线",
        click() { require("electron").shell.openExternal("http://www.zhongyingtougu.com"); }
      },
      {
        label: "联系我们",
        click() { require("electron").shell.openExternal("http://www.zhongyingtougu.com/about/lxwm.html"); }
      },
      {
        type: "separator"
      },
      {
        label: "强制刷新",
        click() {
          win.webContents.reload(); 
        }
      },
      {
        type: "separator"
      },
      {
        label: "清除缓存",
        click() {
          win.webContents.executeJavaScript('if (window.cacher) {window.cacher.clearAll(false);}'); 
          dialog.showMessageBox({
              title: '缓存管理',
              message: '本地缓存清理完毕。',
              buttons: ['确认']
          });
        }
      },
      {
        label: "清除所有数据",
        click() {
          win.webContents.executeJavaScript('if (window.cacher) {window.cacher.clearAll(true);}'); 
          dialog.showMessageBox({
              title: '数据管理',
              message: '本地缓存及用户数据清理完毕。',
              buttons: ['确认']
          });
        }
      }
    ]
  }];

  ipcMain.on("app.opendev", function (event) {
    let win = BrowserWindow.getFocusedWindow();
    win && win.webContents.openDevTools();
  });
  ipcMain.on("app.load", function (event, arg) {
    let win = BrowserWindow.getFocusedWindow();
    win && win.loadURL(arg);
  });
  ipcMain.on("app.update", function (event, arg) {
    autoUpdater.checkForUpdatesAndNotify();
  });

  if (process.platform === "darwin") {
    template[0].submenu.unshift({
      role: "about",
      label: "关于" + APP_NAME
    });

    template.splice(1, 0, {
      label: '编辑',
      submenu: [
          { label: '撤销', accelerator: "CmdOrCtrl+Z", selector: "undo:" },
          { label: '重做', accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
          { type: "separator" },
          { label: '复制', accelerator: "CmdOrCtrl+C", selector: "copy:" },
          { label: '粘贴', accelerator: "CmdOrCtrl+V", selector: "paste:" },
          { label: '剪切', accelerator: "CmdOrCtrl+X", selector: "cut:" },
          { label: '全选', accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
      ]
    });
  }

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
};

const createWindow = () => {
  createMenu();

  // 建立新窗口
  win = new BrowserWindow({
    useContentSize: true,
    width: 1330,
    height: 720,
    minHeight: 600,
    minWidth: 880,
    backgroundColor: "#2e2c29",
    // closable: false,
    webPreferences: {
      webSecurity: false,
      allowRunningInsecureContent: true,
      experimentalFeatures: true,
      experimentalCanvasFeatures: true,
      plugins: true,
      // nodeIntegration: false,
    }
    // show: false
  });
 
  //设置userAgent
  let agent = global['appAgent'] + " (Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Electron/1.8.1)[locale=" + app.getLocale() + "]";
  win.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
    details.requestHeaders['User-Agent'] = agent;
    callback({ cancel: false, requestHeaders: details.requestHeaders });
  });  

  win.loadURL(url.format({
    pathname: "localhost:17258",
    // pathname: "client.html",
    protocol: "http:",
    slashes: true
  }));
  win.maximize();

  // toggle chrome dev tools
  // win.webContents.openDevTools();
  // win.once("ready-to-show", () => win.show()); // 消除空白期闪烁
  // 对资源请求进行差值
  protocol.interceptFileProtocol("file", (req, callback) => {
    // console.log("Intercept File: ", util.inspect(req));
    let url = req.url.substr(7).replace(/\?.*$/ig, "");
    if (url.indexOf("/") === 0 && url.indexOf(__dirname) === -1) {
      url = __dirname + url;
      // console.log("Intercept File: ", url);
      return callback(url);
    }
    // console.log("Intercept File: ", url);
    return callback(url);
  }, err => console.log("Protocol Error: ", err))


  if (process.platform === 'darwin') {
    let forceQuit = false;
    app.on('before-quit', function() {
      forceQuit = true;
    });
    win.on('close', function(event) {
      if (!forceQuit) {
        app.hide();
        event.preventDefault();
        //app.dock.hide();
      }
    });
  } else {
    win.on("closed", () => win = null); // 关闭直接退出
  }
};


app.on("window-all-closed", () => {
  //if (process.platform !== "darwin") {
    app.quit();
  //}
});


function showWindow() {
  if (win === null) {
    createWindow();
  } else {
    win.show();
    if (app.dock && app.dock.show)
      app.dock.show();
  }
}

function checkUpdate(ifShowMsgBox){
  if (process.env['NODE_ENV'] === 'development')
    return;
    
  ifShowUpdateMsgBox = ifShowMsgBox;
  if (isUpdating) return;
  sendStatusToWindow('检查更新...');
  autoUpdater && autoUpdater.checkForUpdatesAndNotify();
}

function sendStatusToWindow(text) {
  let title = APP_NAME + ' V' + app.getVersion();
  if (text != "_no_update") {
      text = ": " + text;
  } else {
      text = ": 当前已是最新版本";
      if (ifShowUpdateMsgBox) {
        dialog.showMessageBox({
            title: '版本检查',
            message: '当前已是最新版本。',
            buttons: ['确认']
        });
      }
      setTimeout(function(){
        win.webContents.executeJavaScript('document.title="' + title + '";');    
      }, 8000);
  }
  win.webContents.executeJavaScript('document.title="' + title + text + '";');    
  log.info(text);
}


app.on("ready", () => {
  createWindow();

  tray = new Tray(path.resolve(__dirname, "static/images/simple_logo.png"));
  tray.setToolTip(APP_NAME);
  tray.on("click", e => {
    showWindow();
  });

  setTimeout(function(){
    checkUpdate(false);
  }, 5000);
});

